<?php

namespace app\admin\controller\user;

use app\admin\controller\Base;
use app\common\model\user\UserModel;
use app\common\model\user\UserLabelModel;

class User extends Base
{
    /**
     * 列表
     */
    public function list()
    {
        $params = request()->only(['page', 'limit', 'field_type', 'field_value', 'label_ids']);
        if (isset($params['field_type']) && !empty($params['field_type']) && isset($params['field_value']) && !empty($params['field_value'])) {
            $where[] = [$params['field_type'], 'like', "%{$params['field_value']}%"];
        }

        $sqlObj = (new UserModel)->where($where ?? []);
        if (isset($params['label_ids']) && !empty($params['label_ids'])) {
            $sqlObj->where("concat(',', label_ids , ',') regexp concat(',',replace('{$params['label_ids']}',',',',|,'),',')");
        }

        $list = $sqlObj->paginate([
            'list_rows' => $params['limit'] ?? 10,
            'page' => $params['page'] ?? 1
        ]);
        foreach ($list->items() as &$v) {
            $v['label_ids'] = (new UserLabelModel)->getNamesByIds($v['label_ids']);
            $v['sex_attr'] = (new UserModel)->sex[$v['sex']];
            $v['url'] = get_file_url($v['head_img']);
        }

        return response_success('', [
            'count' => $list->total(),
            'data' => $list->items()
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        $params = request()->only(['name', 'mobile', 'label_ids', 'head_img', 'sex', 'birthday']);
        $this->validate($params, [
            'name|名称' => 'require',
            'birthday|生日' => 'date',
        ]);

        if ((new UserModel)->where('name', $params['name'])->find()) {
            return response_error('名称已存在');
        }
        if ((new UserModel)->where('name', $params['mobile'])->find()) {
            return response_error('手机号已存在');
        }

        if (empty($params['birthday'])) {
            $params['birthday'] = null;
        }
        $params['create_time'] = date('Y-m-d H:i:s');
        (new UserModel)->insert($params);

        return response_success();
    }

}